<?php
require_once ('config.php');

$userid = $_POST['id'];
$password = $_POST['pw'];
$type = $_POST['type'];
$data = $_POST['data'];
send($userid, $password, $type, $data);

function send($userid, $password, $type, $data) {
	//找gcmID
	$dsn = "mysql:host=" . DB_HOST . ";dbname=" . DB_NAME;
	$db = new PDO($dsn, DB_USER, DB_PASSWORD);

	$rs = $db->prepare("select gcmid from " . TAB_USER . " where userid=:U and password=:P");
	$rs->bindValue(':U', $userid);
	$rs->bindValue(':P', md5($password));
	$rs->execute();
	$rs->setFetchMode(PDO :: FETCH_NUM); //FETCH_ASSOC
	if ($db->errorCode() != '00000') {
		$result = array (
			"result" => "error",
			"cause" => "db_error",
			"info" => $db->errorInfo()
		);
		die(json_encode($result));
	}
	$db = null;

	$result = $rs->fetchall();

	if (empty ($result) || empty ($result[0]) || empty ($result[0][0])) {
		$result = array (
			"result" => "error",
			"cause" => "data_error",
			"info" => "ID or password error."
		);
		die(json_encode($result));
	}
	$gcmid = $result[0][0];

	$apiKey = "AIzaSyACrZ5mWfwaID0Xahttng8ugdlvE5bwywA";
	$regIDs = array (
		$gcmid
	);
	$message = json_encode(array (
		"time" => time(),
		"name" => $userid,
		"data" => $data,
		"type" => $type
	));
	// Set POST variables
	$url = 'https://android.googleapis.com/gcm/send';

	$fields = array (
		'registration_ids' => $regIDs,
		'data' => array (
			"msg" => $message
		),
	);

	$headers = array (
		'Authorization: key=' . $apiKey,
		'Content-Type: application/json'
	);

	// Open connection
	$ch = curl_init();

	// Set the url, number of POST vars, POST data
	curl_setopt($ch, CURLOPT_URL, $url);

	curl_setopt($ch, CURLOPT_POST, true);
	curl_setopt($ch, CURLOPT_HTTPHEADER, $headers);
	curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);

	curl_setopt($ch, CURLOPT_POSTFIELDS, json_encode($fields));

	// Execute post
	$result = curl_exec($ch);

	// Close connection
	curl_close($ch);

	echo $result;
}
?>
